package com.soso.gae.spider.queue.api.impl;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.soso.core.queue.Task;
import com.soso.core.queue.api.QueueService;
import com.soso.core.queue.Method;

public class QueueServiceImpl implements QueueService{

	private com.google.appengine.api.taskqueue.TaskOptions.Method getMethod(Method method){
		if(Method.GET.equals(method)){
			return com.google.appengine.api.taskqueue.TaskOptions.Method.GET;
		}
		if(Method.PULL.equals(method)){
			return com.google.appengine.api.taskqueue.TaskOptions.Method.PULL;
		}
		return com.google.appengine.api.taskqueue.TaskOptions.Method.POST;
	}
	@Override
	public void add(Task task) {
		add(task, null, null);
	}

	@Override
	public void add(Task task, byte[] payload) {
		add(task, payload, null);
	}

	@Override
	public void add(Task task, byte[] payload, String contentType) {
		Queue queue =QueueFactory.getQueue(task.getQueueName());
		TaskOptions taskOptions = TaskOptions.Builder.withUrl(task.getUrl()).method(getMethod(task.getMethod()));
		if(task.getHeaders()!=null){
			taskOptions.headers(task.getHeaders());
		}
		if(payload!=null && contentType!=null){
			taskOptions.payload(payload, contentType);
		}else if(payload!=null){
			taskOptions.payload(payload);
		}
		queue.add(taskOptions);
	}

	@Override
	public void purge(Task task) {
		Queue queue =QueueFactory.getQueue(task.getQueueName());
		queue.purge();
	}

}
